# -*- coding: utf-8 -*-
from db.mysql import MysqlClient
import requests,json
import aiohttp,asyncio
from itertools import product
from common.helper import Helper
from common.config import *
from urllib.parse import urlencode


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "太平境内旅行险"
    # 生成数据
    def genProductInfo(self):
        plan = {
            "year":["0-60"],
            "days":["3d","5d","7d","9d","11d","15d","30d"],
            "people_count":[str(i) for i in range(1,6)],
        }
        for v in product( plan["year"],plan["days"],plan["people_count"]):
            data = Helper.formatProductInfo( plan,v )
            data["accident_death"] = str(100000 * int(data["people_count"]))
            data["accident_medical"] = str(10000* int(data["people_count"]))
            data["tardy_fee"] = "{0}/天".format( str(20 *int( data["people_count"]) ))
            # print( data )
            yield data
    async def requestJson(self,dt):

        payload = self.filterPayload( dt )
        async with aiohttp.ClientSession() as session:
            async with session.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload) as resp:
                res = await resp.text()
                if "计算保费成功" in res:
                    price = Helper.decimalParse( json.loads( res )["totalPremium"] )
                    data = {
                        "name":self.name,
                        "company":"太平洋保险",
                        "price":price
                    }
                    data.update( dt )
                    Helper.mergeTable( self.name , self.mysql,data )

    def filterPayload(self,data=None):
        params = '''
        pageName: productAdd
        goods_id: 62527
        merchant_id: B2C
        toubaoli_money: 
        productCode: 201711141000001
        productId: 6473bc13-a178-44bd-9b79-b8ba189b7ff6
        riskCode: 201711141000000
        productName: 太平境内旅行险
        insuredPrice: 26
        insured.birthday: 
        templateType: 1
        employee_id: 
        channel: GWSC-MENU-M24
        empNo: 
        newsCode: 
        twoMonthInsuredPrice: 52.00
        loginUserId: 
        policy.startDate: 2020-05-01
        policy.endDate: 2020-05-29
        trialBySexAndAge: false
        policy.unit: 03
        person.mobilenum: 承保短信将发送至您的手机
        '''
        payload = Helper.perfectJson( params )
        payload["policy.endDate"] = "2020-05-0{0}".format( data["days"].replace("d","")) if int(data["days"].replace("d",""))<10 else "2020-05-{0}".format( data["days"].replace("d",""))
        payload["policy.unit"] = "0{0}".format( data["people_count"])
        return urlencode( payload ).replace("+","")
    #执行
    def asyncTask(self):
        tasks = [self.requestJson( data ) for data in self.genProductInfo() ]
        event_loop = asyncio.get_event_loop()
        event_loop.run_until_complete(asyncio.gather( *tasks ))
        event_loop.close()
    def test(self):
        data = {'pageName': ' productAdd', 'goods_id': ' 62527', 'merchant_id': ' B2C', 'toubaoli_money': '', 'productCode': ' 201711141000001', 'productId': ' 6473bc13-a178-44bd-9b79-b8ba189b7ff6', 'riskCode': ' 201711141000000', 'productName': ' 太平境内旅行险', 'insuredPrice': ' 26', 'insured.birthday': '', 'templateType': ' 1', 'employee_id': '', 'channel': ' GWSC-MENU-M24', 'empNo': '', 'newsCode': '', 'twoMonthInsuredPrice': ' 52.00', 'loginUserId': '', 'policy.startDate': ' 2020-05-01', 'policy.endDate': '2020-05-30', 'trialBySexAndAge': ' false', 'policy.unit': '05', 'person.mobilenum': ' 承保短信将发送至您的手机'}
        payload = urlencode(data).replace("+","")
        r =requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)
        print( r.text )